#!/usr/bin/env python

from pyraf import iraf
from pyraf.iraf import pysoar
from pysoarlib import createfile_and_write,error

from string import Template
import os

def createtask(taskname,pkgname,rootpkg,verbose):
	d = dict(task=taskname,pkg=pkgname,root=rootpkg)

	#Setting the default filenames
	taskpy  = '%s.py'%taskname
	hlpfile = '%s.hlp'%taskname
	parfile =  '%s.par'%taskname

	#Setting the pathnames for each default files 
	path_pkg = iraf.osfn("%s$%s"%(rootpkg,pkgname))
	path_taskpy    = os.path.join(path_pkg,taskpy)
	path_hlpfile   = os.path.join(path_pkg,hlpfile)
	path_parfile   = os.path.join(path_pkg,parfile)


	template_taskpy = Template('''#!/usr/bin/env python

from pyraf import iraf
from pyraf.iraf import $root
 
# -----------------------------------------------------------
# core algorithm
 
def $task(message):
 
         print message
 
# -----------------------------------------------------------
# main task
 
parfile = iraf.osfn("$root$$$pkg/$task.par")
t = iraf.IrafTaskFactory(taskname="$task",value=parfile,function=$task)
''').safe_substitute(d)
	
	template_parfile = Template('''message,s,a,'Hello world',,,'print message'
mode,s,h,"al"''').safe_substitute(d)

	template_hlpfile = Template('''.help $task Jan 2011 ${root}.${pkg}
.ih
NAME
$task -- Print a message to the terminal
.ih
USAGE
$task message
.ih
PARAMETERS
.ls message
String. The message to be printed to the terminal.
.le
.ih
DESCRIPTION
$task is a basic task which prints a user-defined message to the
terminal or shell. It's only practical purpose is to provide SOAR
software developers with an example of how to install a new PyRAF task
into the SOAR data package.
.ih
EXAMPLES
1. To print the string "The door is ajar":
 
.nf
    cl> $task message='The door is ajar'
.fi
 
2. To print the string the "The auctioneer looks forbidding":
 
.nf
    cl> $task message='The auctioneer looks forbidding'
.fi
.ih
TIME AND DISK REQUIREMENTS
The $task task performs no file I/O or intensive processing. It can
be executed on machines of modest capabilities in no time at all.
.ih
BUGS AND LIMITATIONS
No known bugs.
.ih
Send feedback and bug reports to lfraga@ctio.noao.edu
.ih
SEE ALSO
soartools
.endhelp''').safe_substitute(d)

	#Creating the default files (if they do not exist).
	try:
		createfile_and_write(path_taskpy,template_taskpy)
		createfile_and_write(path_hlpfile,template_hlpfile)
		createfile_and_write(path_parfile,template_parfile)

	except OSError:
		error('OSError:\nTask %s already exist!'%taskname)
		pass
	finalmsg = Template('''
Edit the $pkg.cl to include the lines bellow:

pyexecute("$root$$$pkg/$task.py",verbose=no)
''').safe_substitute(d)
	print finalmsg
	
parfile = iraf.osfn("pysoar$soartools/createtask.par")
t = iraf.IrafTaskFactory(taskname="createtask",value=parfile,function=createtask)
